package net.huadong.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * netty 服务端
 * ws
 */
public class NettyTimeServer {
    public void bind(int port) throws Exception {
        /**
         * 建立两个线程组，一个用于服务端接受客户端连接，另一个用于进行socketChannel的网络读写
         */
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();//创建爱你server对象
            /**
             * ChannelOption.SO_BACKLOG  存放三次握手请求的队列长度
             *
             * ChildChannelHandler 处理IO事件的操作
             */
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChildChannelHandler());

            ChannelFuture channelFuture = bootstrap.bind(port).sync();//绑定且异步启动
            channelFuture.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {

            //增加解码器处理，此处为自定义的请求服务器时间的handler
            socketChannel.pipeline().addLast(new NettyTimeServerHandler());
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        System.out.println("服务端启动，端口：" + port);
        new NettyTimeServer().bind(port);
    }
}
